package model.data.tableModel.sale;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import enums.Status;
import model.data.interfaces.IWriteableToDB;
import model.data.tableModel.TableControl;
import model.data.tableModel.person.Customer;
import model.handler.databaseHandling.QueryFactory;

/**
 * Representation of the table Purchase.
 * <p>
 * Contains information on which <code>Salesday</code> the <code>Purchase</code>
 * was created and for which <code>Customer</code> the <code>Purchase</code> was
 * created.
 * 
 * @version %I%, %G%
 * @see Customer
 * @see Salesday
 */
public final class Purchase implements IWriteableToDB {

	private final static Logger debug = LogManager.getLogger("DEBUG");

	private final int purchaseID;
	private final Salesday salesday;
	private final int billID;

	private boolean paid;
	private Status status;

	/**
	 * Private constructor. Objects of this class must be initialized by the
	 * factory methods.
	 * 
	 * @param purchaseID
	 * @param paid
	 * @param salesday
	 * @param customerID
	 * @param status
	 */
	private Purchase(int billID, int purchaseID, boolean paid, Salesday salesday, Status status) {
		assert billID >= 0;
		assert purchaseID >= 0;
		assert salesday != null;

		this.purchaseID = purchaseID;
		this.paid = paid;
		this.salesday = salesday;
		this.billID = billID;
		this.status = status;
	}

	@Override
	public String toString() {
		return "PurchaseID: " + purchaseID + "Salesday: " + salesday + "BillID: " + billID + "Status: " + status.toString();
	}

	/**
	 * Initializes an existing Purchase by the data fetched from the database.
	 * 
	 * @param purchaseID
	 * @param paid
	 * @param salesday
	 * @param customerID
	 * @param status
	 * @return Purchase
	 */
	public static Purchase createExistingPurchase(final int billID, final int purchaseID, final boolean paid, final Salesday salesday,
			final Status status) {
		debug.debug("Existing Purchase created ID: " + purchaseID);
		return new Purchase(billID, purchaseID, paid, salesday, status);
	}

	/**
	 * Creates a new Purchase
	 * 
	 * @param paid
	 * @param salesday
	 * @param customerID
	 * @param status
	 * @return a new Purchase
	 */
	public static Purchase createNewPurchase(final int billID, final boolean paid, final Salesday salesday, final Status status) {
		int id = TableControl.getPurchaseCounter();
		debug.debug("New Purchase created ID: " + id);
		return new Purchase(billID, id , paid, salesday, status);
	}

	@Override
	public boolean writeToDB() {
		return QueryFactory.writePurchaseToDB(billID, purchaseID, paid, salesday.getID(), status);
	}

	@Override
	public boolean writeUpdateToDB() {
		// TODO implement
		return false;
	}
	
	/* GETTER AND SETTER BELOW */	

	public int getPurchaseID() {
		return purchaseID;
	}

	public boolean isPaid() {
		return paid;
	}

	public Salesday getSalesday() {
		return salesday;
	}

	public Status isStatus() {
		return status;
	}
}
